#include "tcpserver.h"
#include "ui_tcpserver.h"
#include <QMessageBox>
#include <QByteArray>
#include<QDebug>
#include<QHostAddress>
TcpServer::TcpServer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TcpServer)
{
    ui->setupUi(this);
    loadConfig();

    //connect(&MyTcpServer::getInstance(),&QTcpServer::newConnection,this,&TcpServer::connectedSuc);

    //单例模式
    MyTcpServer::getInstance().listen(QHostAddress(m_strIP),m_usPort);
}

TcpServer::~TcpServer()
{
    delete ui;
}

void TcpServer::loadConfig()
{
    QFile file(":/server.config");
    if(file.open(QIODevice::ReadOnly)){
        QByteArray baData = file.readAll();
        QString strData = baData.toStdString().c_str();
        QStringList strList = strData.split("\r\n");
        file.close();
        m_strIP = strList.at(0);
        m_usPort = strList.at(1).toUShort();

    }
    else
    {
        QMessageBox::critical(this,"open config","open config failed");
    }
}

void TcpServer::connectedSuc()
{
    QMessageBox::information(this,"服务器监听","服务器监听到客户端连接请求！");
   // MyTcpSocket *pTcpSocket = new MyTcpSocket;
    QTcpSocket *sc = MyTcpServer::getInstance().nextPendingConnection();
    connect(sc,&QTcpSocket::readyRead,this,[=]{
        //qDebug()<<this->bytesAvailable();
        uint uiPDULen = 0;
        //先读取消息的总长度信息(4个字节），读取的总长度为sizeof(uint)
        sc->read((char*)&uiPDULen,sizeof(uint));
        //实际消息长度为总长度减去结构体前面几个备注信息字节
        uint uiMsgLen = uiPDULen - sizeof(PDU);
        //申请一个空间用于接收实际消息
        PDU* pdu = mkPDU(uiMsgLen);
        //读取实际消息，(char*)pdu + sizeof(uint)为存放接收数据的起始地址
        //(char*)pdu + sizeof(uint)为地址偏移，因为前面已经接收了uint个字节的数据，所以要往后挪动uint个字节
        sc->read((char*)pdu + sizeof(uint),uiPDULen - sizeof(uint));
        qDebug()<<pdu->uiMsgType<<"   "<<pdu->caMsg;
    });
    //pTcpSocket->m_tcpSocketList.append(sc);
}

